package SocketTest.IO;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 双向通信socket客户端简单示例
 * @author chenjunjie
 * @since 2018-04-17
 */
public class Client {
    public static void main(String[] args) throws IOException {
        Client client = new Client();
        client.sendMessage();
    }

    /**
     * 客户端与服务端建立连接只需要一个socket对象即可
     */
    protected void sendMessage() throws IOException {
        String host = "127.0.0.1";
        int port = 5200;
        Socket clientSocket = new Socket(host,port);
        /*
         //上面一句大致功能如下几句，与上面的唯一区别是可以为客户端指定端口
         Socket clientSocket = new Socket();
         clientSocket.bind(new InetSocketAddress(55534));
         clientSocket.connect(new InetSocketAddress(host, port));
        */


        //发送信息
        OutputStream out = clientSocket.getOutputStream();
        out.write("hello hello, 请求服务端1分钟之后，进行某某操作".getBytes("UTF-8"));

        //关键点!!
        //相当于给流中加入一个结束标记-1,用于关闭客户端输出流
        //从而保证在服务端那边在读数据完成后，再进行下一步处理。
        //或者通过约定符号的方式来通知客户端已经输入完毕，如在输入结尾加入“end”字符串
        clientSocket.shutdownOutput();

        //接收信息
        InputStream in = null;
        in = clientSocket.getInputStream();
        StringBuilder sb = new StringBuilder();
        int k;
        byte[] bytes = new byte[1024];
        while((k=in.read(bytes)) != -1){
            sb.append(new String(bytes, 0, k, "UTF-8"));
        }
        System.out.println("get message from server: " + sb);

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        out.close();
        in.close();
        System.out.println("关闭客户端");
        clientSocket.close();
    }

}
